////
////  WeatherViewController.m
////  SoutheastAsia
////
////  Created by rimi on 16/1/6.
////  Copyright © 2016年 zlj. All rights reserved.
////
//
//  WeatherViewController.m
//  SoutheastAsia
//
//  Created by rimi on 16/1/6.
//  Copyright © 2016年 zlj. All rights reserved.
//

#import "WeatherViewController.h"
#import <Masonry.h>
#import "WetherModel.h"
#import "WeatherTableViewCell.h"

#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height;
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width;
#define CAPITAL_NAME @"曼谷",@"河内",@"吉隆坡",@"新加坡",@"金边",@"仰光",@"万象",@"斯里巴加湾市",@"雅加达",@"马尼拉"

@interface WeatherViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) CALayer *backgroundLayer;

@property (nonatomic, strong) UIButton *backButton;

@property (nonatomic, strong) UIView *wetherView;
@property (nonatomic, strong) UILabel *temperatureLabel;
@property (nonatomic, strong) UIImageView *temperatureCircle;

@property (nonatomic, strong) WetherModel *wetherModel;
@property (nonatomic, strong) UILabel *cityLabel;
@property (nonatomic, strong) UIImageView *arrowImageView;

@property (nonatomic, strong) UISwipeGestureRecognizer *downSwipeGesture;
@property (nonatomic, strong) UISwipeGestureRecognizer *upSwipeGesture;

@property (nonatomic, strong) UISwipeGestureRecognizer *dismissSwipeGesture;

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonatomic, strong) UIVisualEffectView *visualEffectView;
@property (nonatomic, strong) UIBlurEffect *blur;

@property (nonatomic, strong) NSArray *capitals;

@end

@implementation WeatherViewController

- (void)dealloc {
    [self removeObserver];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addGestureRecognizer:self.dismissSwipeGesture];
    [self.view.layer addSublayer:self.backgroundLayer];
    [self.view addSubview:self.wetherView];
    [self.view addSubview:self.backButton];

    [self.wetherView addSubview:self.cityLabel];
    [self.wetherView addSubview:self.temperatureLabel];
    [self.wetherView addSubview:self.temperatureCircle];
    [self.wetherView addSubview:self.arrowImageView];
    [self.wetherView addSubview:self.tableView];
    [self addContraint];
    
    [self registerObserver];
    [self.wetherModel temperatureListCity:self.capitals[self.countryIndex]];
}

#pragma mark -- KVO

- (void)registerObserver {
    [self.wetherModel addObserver:self forKeyPath:@"temperatureList" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)removeObserver {
    [self.wetherModel removeObserver:self forKeyPath:@"temperatureList" context:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    self.dataSource = self.wetherModel.temperatureList[@"daily_forecast"];
    [self.tableView reloadData];
    self.temperatureLabel.text = self.wetherModel.temperatureList[@"daily_forecast"][0][@"tmp"][@"max"];
}

#pragma mark -- private methods

- (void)addContraint {
    [self.wetherView mas_makeConstraints:^(MASConstraintMaker *make) {
        double top = [UIScreen mainScreen].bounds.size.height * 2 / 3;
        make.top.equalTo(@(top));
        make.size.mas_equalTo(CGSizeMake(CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds)));
    }];
    
    [self.temperatureLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        double top = [UIScreen mainScreen].bounds.size.height / 8;
        make.top.equalTo(@(top));
        make.left.equalTo(@220);
        make.size.mas_equalTo(CGSizeMake(100, 80));
    }];
    
    [self.cityLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        double top = [UIScreen mainScreen].bounds.size.height / 8 + 10;
        make.top.equalTo(@(top));
        make.left.equalTo(@10);
        make.size.mas_equalTo(CGSizeMake(200, 40));
    }];
    
    [self.temperatureCircle mas_makeConstraints:^(MASConstraintMaker *make) {
        double top = [UIScreen mainScreen].bounds.size.height / 8;
        make.top.equalTo(@(top));
        make.left.equalTo(@320);
        make.size.mas_equalTo(CGSizeMake(30, 30));
    }];
    
    [self.arrowImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        double top = [UIScreen mainScreen].bounds.size.height / 8 + 60;
        double midPoint = [UIScreen mainScreen].bounds.size.width / 2;
        make.top.equalTo(@(top));
        make.left.equalTo(@(midPoint - 64));
        make.size.mas_equalTo(CGSizeMake(100, 80));
    }];
}

#pragma mark -- action/callback

- (void)upSwipeGesture:(UISwipeGestureRecognizer *)gesture {
    [self.view insertSubview:self.visualEffectView belowSubview:self.wetherView];
    [UIView animateWithDuration:0.3 animations:^{
        self.arrowImageView.alpha = 0;
        [self.wetherView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(CGRectGetMinY(self.view.bounds));
        }];
        [self.wetherView layoutIfNeeded];
    }];
}

- (void)downSwipeGesture:(UISwipeGestureRecognizer *)gesture {
    [self.visualEffectView removeFromSuperview];
    [UIView animateWithDuration:0.3 animations:^{
        self.arrowImageView.alpha = 1.0;
        [self.wetherView mas_updateConstraints:^(MASConstraintMaker *make) {
            double top = [UIScreen mainScreen].bounds.size.height * 2 / 3;
            make.top.equalTo(@(top));
        }];
        [self.wetherView layoutIfNeeded];
    }];
}

- (void)dismissSwipeGesture:(UISwipeGestureRecognizer *)gesture {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)backButtonTaped:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -- UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WeatherTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"  forIndexPath:indexPath];
    [cell loadDataList:self.dataSource[indexPath.row]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds) - 40, 30)];
    //设置圆角
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:headerView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(8, 8)];
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.frame = headerView.bounds;
    shapeLayer.path = maskPath.CGPath;
    headerView.layer.mask = shapeLayer;
    
    headerView.backgroundColor = [UIColor colorWithWhite:0.702 alpha:0.560];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, CGRectGetWidth(headerView.bounds), CGRectGetHeight(headerView.bounds))];
    label.text = @"Forecast";
    label.font= [UIFont systemFontOfSize:20];
    label.textColor = [UIColor whiteColor];
    [headerView addSubview:label];
    
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}

#pragma mark -- UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark -- getter

- (UIButton *)backButton {
    if (!_backButton) {
        _backButton = ({
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(10, 30, 60, 40);
            [button setImage:[UIImage imageNamed:@"返回按钮.png"] forState:UIControlStateNormal];
            [button addTarget:self action:@selector(backButtonTaped:) forControlEvents:UIControlEventTouchUpInside];
            button;
        });
    }
    return _backButton;
}

- (WetherModel *)wetherModel {
    if (!_wetherModel) {
        _wetherModel = [[WetherModel alloc] init];
    }
    return _wetherModel;
}

- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataSource;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = ({
            UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(20, [UIScreen mainScreen].bounds.size.height * 0.35, CGRectGetWidth(self.view.bounds) - 40, [UIScreen mainScreen].bounds.size.height * 0.85) style:UITableViewStyleGrouped];
            [tableView registerClass:[WeatherTableViewCell class] forCellReuseIdentifier:@"cell"];
            tableView.rowHeight = [UIScreen mainScreen].bounds.size.height * 0.07;
            tableView.delegate = self;
            tableView.dataSource = self;
            tableView.tableFooterView = [[UIView alloc] init];
            tableView.scrollEnabled = NO;
            tableView.backgroundColor = [UIColor clearColor];
            tableView.separatorColor = [UIColor clearColor];
            tableView;
        });
    }
    return _tableView;
}

- (UIView *)wetherView {
    if (!_wetherView) {
        _wetherView = [[UIView alloc] init];
        _wetherView.backgroundColor = [UIColor clearColor];
        [_wetherView addGestureRecognizer:self.downSwipeGesture];
        [_wetherView addGestureRecognizer:self.upSwipeGesture];
    }
    return _wetherView;
}

- (UILabel *)temperatureLabel {
    if (!_temperatureLabel) {
        _temperatureLabel = [[UILabel alloc] init];
        _temperatureLabel.textAlignment = NSTextAlignmentLeft;
        _temperatureLabel.font = [UIFont systemFontOfSize:80];
        _temperatureLabel.textColor = [UIColor whiteColor];
    }
    return _temperatureLabel;
}

- (UILabel *)cityLabel {
    if (!_cityLabel) {
        _cityLabel = [[UILabel alloc] init];
        _cityLabel.textColor = [UIColor whiteColor];
        _cityLabel.textAlignment = NSTextAlignmentCenter;
        _cityLabel.font = [UIFont systemFontOfSize:30];
        _cityLabel.numberOfLines = 2;
        _cityLabel.text = self.city;
    }
    return _cityLabel;
}

- (UIImageView *)temperatureCircle {
    if (!_temperatureCircle) {
        _temperatureCircle = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"摄氏度.png"] highlightedImage:nil];
        
    }
    return _temperatureCircle;
}

- (UIImageView *)arrowImageView {
    if (!_arrowImageView) {
        _arrowImageView = [[UIImageView alloc] init];
        _arrowImageView.image = [UIImage imageNamed:@"向上.png"];
    }
    return _arrowImageView;
}

- (UISwipeGestureRecognizer *)downSwipeGesture {
    if (!_downSwipeGesture) {
        _downSwipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(downSwipeGesture:)];
        _downSwipeGesture.direction = UISwipeGestureRecognizerDirectionDown;
    }
    return _downSwipeGesture;
}

- (UISwipeGestureRecognizer *)upSwipeGesture {
    if (!_upSwipeGesture) {
        _upSwipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(upSwipeGesture:)];
        _upSwipeGesture.direction = UISwipeGestureRecognizerDirectionUp;
    }
    return _upSwipeGesture;
}

- (UISwipeGestureRecognizer *)dismissSwipeGesture {
    if (!_dismissSwipeGesture) {
        _dismissSwipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(dismissSwipeGesture:)];
        _dismissSwipeGesture.direction = UISwipeGestureRecognizerDirectionDown;
    }
    return _dismissSwipeGesture;
}

- (CALayer *)backgroundLayer{
    if (!_backgroundLayer) {
        _backgroundLayer = [CALayer layer];
        _backgroundLayer.frame = self.view.bounds;
        _backgroundLayer.contents = (__bridge id)[UIImage imageNamed:@"背景.png"].CGImage;
    }
    return _backgroundLayer;
}

- (UIVisualEffectView *)visualEffectView {
    if (!_visualEffectView) {
        _visualEffectView = [[UIVisualEffectView alloc] initWithEffect:self.blur];
        _visualEffectView.frame = self.view.frame;
    }
    return _visualEffectView;
}

- (UIBlurEffect *)blur {
    if (!_blur) {
        _blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    }
    return _blur;
}

- (NSArray *)capitals {
    if (!_capitals) {
        _capitals = [NSArray arrayWithObjects:CAPITAL_NAME, nil];
    }
    return _capitals;
}

@end
